﻿using System;
using System.IO;
using System.Net;
using System.Text;
using agsXMPP;
using agsXMPP.protocol.client;
using sharpxbot.Core.Security;
using sharpxbot.Plugins.Base;
using sharpxbot.Plugins.Context;

namespace sharpxbot.Core.Plugins
{
    public class WebLinksPlugin : AbstractPlugin
    {
        private static readonly Guid PluginGuid = new Guid("17381042-9d4a-4e78-84c0-4c4b39348a43");

        public WebLinksPlugin(IPluginContext context)
            : base(context)
        {
        }

        public override PluginPermissions NeededPermissions
        {
            get { return PluginPermissions.Everyone; }
        }

        public override string Name
        {
            get { return "WebLinksPlugin"; }
        }

        public override string Author
        {
            get { return "tillias"; }
        }

        public override Guid GUID
        {
            get { return PluginGuid; }
        }

        public override string Description
        {
            get { return "Automatically shows short info about web links typed in group-chat"; }
        }

        public override string Usage
        {
            get { return "send plain url"; }
        }

        public override void ProcessMessage(Message message)
        {
            if (message != null)
            {

                var uri = TryParseUri(message.Body);
                if (uri != null)
                {
                    try
                    {
                        var request = WebRequest.Create(uri);
                        var response = request.GetResponse();
                        if (response.ContentType.StartsWith("text/html"))
                        {
                            var encParsed = response.ContentType.Split(new char[] { '=' });
                            if (encParsed != null && encParsed.Length == 2)
                            {
                                var charset = encParsed[1];
                                var encoding = Encoding.GetEncoding(charset);

                                using (var stream = response.GetResponseStream())
                                {
                                    using (var reader = new StreamReader(stream, encoding))
                                    {
                                        var content = reader.ReadToEnd();
                                        var title = ParseTitle(content);
                                        if (title != null)
                                        {
                                            Message jabberResponse = new Message()
                                            {
                                                To = message.From,
                                                Type = message.Type,
                                                Body = String.Format("Link above is about: {0}", title)
                                            };

                                            if (message.Type == MessageType.groupchat)
                                            {
                                                jabberResponse.To = new Jid(message.From.Bare);
                                            }

                                            Context.Channel.Send(jabberResponse);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch { }
                }
                //Message response = new Message()
                //{
                //    To = new Jid(Context.OwnerJid),
                //    Type = MessageType.chat,
                //    Body = "Hello owner!"
                //};

                //Context.Channel.Send(response);
            }
        }

        public override void ProcessPresence(Presence presence)
        {
            //nothing todo
        }

        private System.Uri TryParseUri(string messageBody)
        {
            if (String.IsNullOrEmpty(messageBody))
                return null;

            foreach (var word in messageBody.Split(new char[] { ' ' }))
            {
                try
                {
                    return new System.Uri(word);
                }
                catch { }
            }

            return null;
        }

        private string ParseTitle(string content)
        {
            if (String.IsNullOrEmpty(content))
                return null;

            string result = null;

            string titleBanner = "<title>";
            string titleEndBanner = "</title>";

            var spos = content.IndexOf(titleBanner);
            var epos = content.IndexOf(titleEndBanner);

            if (spos < epos)
            {
                try
                {
                    result = content.Substring(spos + titleBanner.Length, epos - spos - titleEndBanner.Length + 1).Trim();
                }
                catch { }
            }
            
            return result;
        }

    }
}
